/*
 * @Author: zhengzhuang
 * @since: 2020-01-08 15:33:11
 * @lastTime: 2020-02-29 17:19:02
 * @LastAuthor: zhengzhuang
 * @FilePath: /C20Driver/lib/pages/carpool_page/carpool_trip.dart
 * @message: 顺风车行程行程 CarpoolTrip
 */
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:C20Driver/config/app_share.dart';
import 'package:C20Driver/model/get_free_ride_order_data.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:C20Driver/service/request.dart';
import 'package:C20Driver/utils/permission_handler.dart';
import 'package:C20Driver/widget/app_share.dart';
import 'package:C20Driver/widget/spinkit.dart';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';

var markerList = [];
var iconList = [
  'assets/icon/startingPointIcon.png',
  'assets/icon/endIcon.png',
];

class CarpoolTrip extends StatefulWidget {
  final String id;
  CarpoolTrip({this.id});
  @override
  _CarpoolTripState createState() => _CarpoolTripState();
}

class _CarpoolTripState extends State<CarpoolTrip> {
  AmapController _amapController;
  List<Marker> _markers = [];

  var _getData;

  @override
  void initState() {
    super.initState();
    _getData = getFreeRideOrderDataFun();
  }

  Future getFreeRideOrderDataFun() async {
    return await Request.getFreeRideOrderDataFun(widget.id);
  }

  /// 取消行程
  _cancelFreeRideOrder() {
    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('行程取消'),
          content: Text('您确认要取消当前行程?'),
          actions: <Widget>[
            FlatButton(
              child: Text('取消行程'),
              onPressed: () {
                Navigator.of(context).pop();
                Request.cancelFreeRideOrder(context: context, id: widget.id);
              },
            ),
            FlatButton(
              child: Text('再想想'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    ).then((val) {
      print(val);
    });
  }

  /// 订单完成
  void _orderFulfillment(String id) {
    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('行程完成'),
          content: Text('请确认是否送完所有乘客?'),
          actions: <Widget>[
            FlatButton(
              child: Text('行程完成'),
              onPressed: () {
                Request.orderFulfillment(context, id);
              },
            ),
            FlatButton(
              child: Text('还没有'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('顺风车行程'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.delete),
            onPressed: () => _cancelFreeRideOrder(),
          ),
          InkWell(
            child: Container(
              height: ScreenUtil().setWidth(100.0),
              padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(10.0),
                right: ScreenUtil().setWidth(10.0),
              ),
              child: Row(
                children: <Widget>[
                  Icon(Icons.share,
                      size: ScreenUtil().setSp(30.0), color: Colors.white),
                  SizedBox(width: ScreenUtil().setWidth(10.0)),
                  Text('分享',
                      style: TextStyle(
                        fontSize: ScreenUtil().setSp(30.0),
                        color: Colors.white,
                      ))
                ],
              ),
            ),
            onTap: () =>
                AppShare.share(context, AppShareCode().carpoolShare, widget.id),
          )
        ],
      ),
      body: FutureBuilder(
        future: _getData,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            GetFreeRideOrderData dataInfo =
                GetFreeRideOrderData.fromJson(snapshot.data);
            markerList = [
              {
                'iconImage': 'assets/icon/startingPointIcon.png',
                'laction': LatLng(num.parse(dataInfo.depLatitude),
                    num.parse(dataInfo.depLongitude)),
              },
              {
                'iconImage': 'assets/icon/endIcon.png',
                'laction': LatLng(num.parse(dataInfo.destLatitude),
                    num.parse(dataInfo.destLongitude)),
              },
            ];
            return Container(
              child: Stack(
                children: <Widget>[
                  Container(
                    padding:
                        EdgeInsets.only(bottom: ScreenUtil().setWidth(450.0)),
                    child: AmapView(
                      showZoomControl: false,
                      showCompass: true,
                      // 中心点坐标
                      centerCoordinate: LatLng(
                          double.parse(dataInfo.depLatitude),
                          double.parse(dataInfo.depLongitude)),
                      // 缩放级别
                      onMapCreated: (controller) async {
                        _amapController = controller;
                        if (await PermissionHandlerX.position(context)) {
                          /// 两点直线距离
                          await _amapController?.addPolyline(PolylineOption(
                            latLngList: [
                              LatLng(num.parse(dataInfo.depLatitude),
                                  num.parse(dataInfo.depLongitude)),
                              LatLng(num.parse(dataInfo.destLatitude),
                                  num.parse(dataInfo.destLongitude)),
                            ],
                            width: 10,
                            lineCapType: LineCapType.Square,
                            strokeColor: Colors.green,
                          ));

                          /// 设置两点图片
                          final markers = await _amapController?.addMarkers(
                            [
                              for (int i = 0; i < 2; i++)
                                MarkerOption(
                                  latLng: markerList[i]['laction'],
                                  widget: Container(
                                    width: ScreenUtil().setWidth(100.0),
                                    height: ScreenUtil().setWidth(100.0),
                                    alignment: Alignment.topCenter,
                                    child: Image.asset(
                                      markerList[i]['iconImage'],
                                      width: ScreenUtil().setWidth(50.0),
                                      height: ScreenUtil().setWidth(50.0),
                                      fit: BoxFit.contain,
                                    ),
                                  ),
                                  anchorV: 0.5,
                                  anchorU: 0.5,
                                  draggable: true,
                                ),
                            ],
                          );
                          _markers.addAll(markers);

                          /// 将指定的经纬度列表(包括但不限于marker, polyline, polygon等)调整至同一屏幕中显示
                          List<LatLng> arr = [
                            LatLng(num.parse(dataInfo.depLatitude),
                                num.parse(dataInfo.depLongitude)),
                            LatLng(num.parse(dataInfo.destLatitude),
                                num.parse(dataInfo.destLongitude))
                          ];
                          _amapController?.zoomToSpan(arr,
                              padding:
                                  EdgeInsets.all(ScreenUtil().setWidth(200.0)));
                        }
                      },
                      onMapClicked: (latLng) {
                        return;
                      },
                    ),
                  ),
                  Positioned(
                    bottom: ScreenUtil().setWidth(20.0),
                    left: ScreenUtil().setWidth(20.0),
                    child: Container(
                      width: ScreenUtil().setWidth(710.0),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius:
                              BorderRadius.circular(ScreenUtil().setSp(10.0)),
                          boxShadow: <BoxShadow>[
                            BoxShadow(
                                color: Colors.black12,
                                blurRadius: ScreenUtil().setSp(20.0))
                          ]),
                      child: Column(
                        children: <Widget>[
                          // Container(
                          //   height: ScreenUtil().setWidth(120.0),
                          //   padding: EdgeInsets.only(
                          //     left: ScreenUtil().setWidth(30.0),
                          //     right: ScreenUtil().setWidth(30.0),
                          //   ),
                          //   child: Row(
                          //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          //     children: <Widget>[
                          //       Text('刘师傅${widget.id}', style: TextStyle(
                          //         fontSize: ScreenUtil().setSp(28.0),
                          //         color: Colors.black87
                          //       )),
                          //       Text('鲁BA54H6 大众捷达·白色', style: TextStyle(
                          //         fontSize: ScreenUtil().setSp(24.0),
                          //         color: Colors.black87
                          //       )),
                          //     ],
                          //   ),
                          // ),
                          // Divider(height: ScreenUtil().setWidth(2.0), color: Color.fromARGB(255, 242, 242, 242)),
                          Container(
                            padding: EdgeInsets.only(
                              left: ScreenUtil().setWidth(30.0),
                              right: ScreenUtil().setWidth(30.0),
                            ),
                            child: Column(
                              children: <Widget>[
                                SizedBox(height: ScreenUtil().setWidth(30.0)),
                                Row(
                                  children: <Widget>[
                                    Icon(
                                      Icons.access_time,
                                      size: ScreenUtil().setWidth(18.0),
                                      color: Color.fromARGB(255, 205, 205, 205),
                                    ),
                                    SizedBox(
                                        width: ScreenUtil().setWidth(10.0)),
                                    Text(
                                      '${dataInfo.departureDate}',
                                      style: TextStyle(
                                        fontSize: ScreenUtil().setSp(32.0),
                                        color: Color.fromARGB(255, 51, 51, 51),
                                      ),
                                    ),
                                  ],
                                ),
                                SizedBox(height: ScreenUtil().setWidth(15.0)),
                                Row(
                                  children: <Widget>[
                                    Container(
                                      width: ScreenUtil().setWidth(18.0),
                                      height: ScreenUtil().setWidth(18.0),
                                      decoration: BoxDecoration(
                                        color:
                                            Color.fromARGB(255, 36, 142, 247),
                                        shape: BoxShape.circle,
                                      ),
                                    ),
                                    SizedBox(
                                        width: ScreenUtil().setWidth(10.0)),
                                    Container(
                                      width: ScreenUtil().setWidth(600.0),
                                      child: Text(
                                        '${dataInfo.depAre}',
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontSize: ScreenUtil().setSp(32.0),
                                          color:
                                              Color.fromARGB(255, 51, 51, 51),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                SizedBox(height: ScreenUtil().setWidth(15.0)),
                                Row(
                                  children: <Widget>[
                                    Container(
                                      width: ScreenUtil().setWidth(18.0),
                                      height: ScreenUtil().setWidth(18.0),
                                      decoration: BoxDecoration(
                                        color: Color.fromARGB(255, 255, 153, 0),
                                        shape: BoxShape.circle,
                                      ),
                                    ),
                                    SizedBox(
                                        width: ScreenUtil().setWidth(10.0)),
                                    Container(
                                      width: ScreenUtil().setWidth(600.0),
                                      child: Text(
                                        '${dataInfo.destArea}',
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontSize: ScreenUtil().setSp(32.0),
                                          color:
                                              Color.fromARGB(255, 51, 51, 51),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                SizedBox(height: ScreenUtil().setWidth(30.0)),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  children: <Widget>[
                                    MaterialButton(
                                      child: Text('同行乘客',
                                          style: TextStyle(
                                              fontSize:
                                                  ScreenUtil().setSp(34.0),
                                              color: Colors.white)),
                                      minWidth: ScreenUtil().setWidth(200.0),
                                      height: ScreenUtil().setWidth(100.0),
                                      color: Color.fromARGB(255, 255, 153, 0),
                                      onPressed: () => NavigatorUtil.jump(
                                          context,
                                          '/carpoolFellowPassengers?id=${dataInfo.id}'),
                                    ),
                                    MaterialButton(
                                      child: Text('补票收款',
                                          style: TextStyle(
                                              fontSize:
                                                  ScreenUtil().setSp(34.0),
                                              color: Colors.white)),
                                      minWidth: ScreenUtil().setWidth(200.0),
                                      height: ScreenUtil().setWidth(100.0),
                                      color: Color.fromARGB(255, 78, 79, 95),
                                      onPressed: () => NavigatorUtil.jump(
                                          context,
                                          '/setCollectionAmount?orginPoint=${Uri.encodeComponent(dataInfo.destArea)}&endPoint=${Uri.encodeComponent(dataInfo.depAre)}&unitPrice=${dataInfo.totalPrice}'),
                                    ),
                                    MaterialButton(
                                      child: Text('当前行程',
                                          style: TextStyle(
                                              fontSize:
                                                  ScreenUtil().setSp(34.0),
                                              color: Colors.white)),
                                      minWidth: ScreenUtil().setWidth(200.0),
                                      height: ScreenUtil().setWidth(100.0),
                                      color: Color.fromARGB(255, 78, 79, 95),
                                      onPressed: () => NavigatorUtil.jump(
                                          context,
                                          '/lookingPassengers?id=${dataInfo.id}&orderId=${widget.id}&depArea=${Uri.encodeComponent(dataInfo.depAre)}&destArea=${Uri.encodeComponent(dataInfo.destArea)}'),
                                    ),
                                  ],
                                ),
                                SizedBox(height: ScreenUtil().setWidth(15.0)),
                                MaterialButton(
                                  child: Text('订单完成',
                                      style: TextStyle(
                                          fontSize: ScreenUtil().setSp(34.0),
                                          color: Colors.white)),
                                  minWidth: ScreenUtil().setWidth(200.0),
                                  height: ScreenUtil().setWidth(100.0),
                                  color: Color.fromARGB(255, 255, 153, 0),
                                  onPressed: () =>
                                      _orderFulfillment(dataInfo.id),
                                ),
                                SizedBox(height: ScreenUtil().setWidth(15.0)),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            );
          } else {
            return Spinkit();
          }
        },
      ),
    );
  }

  @override
  void dispose() {
    _amapController.dispose();
    // _amapController = null;
    super.dispose();
  }
}
